package com.gitee.qdbp.general.common.web.controller.files;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.gitee.qdbp.base.annotation.OperateRecord;
import com.gitee.qdbp.tools.files.ImageTools;
import com.gitee.qdbp.tools.utils.JsonTools;
import com.gitee.qdbp.tools.utils.PropertyTools;
import com.gitee.qdbp.tools.utils.StringTools;

/**
 * 二维码图片<br>
 * 示例: qrcode/link/details/xxx/10001.png<br>
 * 配置: site.manager.outer.url = http://www.abc.com/m/<br>
 * 配置: qrcode.xxx = {config:site.manager.outer.url}xxx/{id}.html<br>
 * 结果: 返回二维码图片, 扫描结果为http://www.abc.com/m/xxx/10001.html<br>
 *
 * @author zhaohuihua
 * @version 170704
 */
@Controller
@RequestMapping("qrcode/link")
@OperateRecord(enable = false)
public class QrCodeLinkImageController {

    /** 日志对象 **/
    private static final Logger log = LoggerFactory.getLogger(QrCodeLinkImageController.class);

    @Autowired
    @Qualifier("setting")
    private Properties setting;

    @RequestMapping(value = "details/{type}/{id}.png", method = RequestMethod.GET)
    public void qrcode(@PathVariable("type") String type, @PathVariable("id") String id, HttpServletRequest request,
            HttpServletResponse response) {

        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("id", id);

        generateQrCode(type, params, request, response);
    }

    @RequestMapping(value = "details/{type}/{module}/{id}.png", method = RequestMethod.GET)
    public void qrcode(@PathVariable("type") String type, @PathVariable("module") String module,
            @PathVariable("id") String id, HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("module", module);
        params.put("id", id);

        generateQrCode(type, params, request, response);
    }

    @RequestMapping(value = "details/{type}/{module}/{channel}/{id}.png", method = RequestMethod.GET)
    public void qrcode(@PathVariable("type") String type, @PathVariable("module") String module,
            @PathVariable("channel") String channel, @PathVariable("id") String id, HttpServletRequest request,
            HttpServletResponse response) {

        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("module", module);
        params.put("channel", channel);
        params.put("id", id);

        generateQrCode(type, params, request, response);
    }

    private void generateQrCode(String type, Map<String, Object> params, HttpServletRequest request,
            HttpServletResponse response) {

        try {
            // 根据类型读取配置项
            String string = PropertyTools.getString(setting, "qrcode." + type, true);
            String content = StringTools.format(string, params);
            int size = getIntegerValue("qrcode." + type + ".size", 200);
            int margin = getIntegerValue("qrcode." + type + ".margin", 0);

            // 生成二维码并输出
            response.setContentType("image/png");
            OutputStream os = response.getOutputStream();
            ImageTools.generateQrCode(content, size, margin, os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error("Failed to generate qr code, type={}, params={}", type, JsonTools.toJsonString(params), e);
        }
    }

    private int getIntegerValue(String key, int defvalue) {
        if (setting.containsKey(key)) {
            String value = setting.getProperty(key);
            try {
                return Integer.valueOf(value);
            } catch (Exception ignore) {
                log.warn("Config value '{} = {}' can't convert to integer number.", key, value);
            }
        }
        return defvalue;
    }
}
